package com.koron.ticket.work.logicticket.electricalfirst.service;

import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.ticket.work.common.bean.FifteenTables;
import com.koron.ticket.work.common.bean.Print;
import com.koron.ticket.work.common.service.FifteenTablesService;
import com.koron.ticket.work.common.service.OrderChangeStatusService;
import com.koron.ticket.work.enums.TicketNodeStatus;
import com.koron.ticket.work.enums.TicketStatus;
import com.koron.ticket.work.enums.TicketType;
import com.koron.ticket.work.enums.WorkFlowType;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workticket.bean.WorkTicket;
import com.koron.ticket.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.work.workticket.service.WorkTicketService;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ElectricalFirstService {

    @Autowired
    private FifteenTablesService fifteenTablesService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkTicketService workTicketService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkEndService workEndService;

    // 变更工单状态
    @Autowired
    private OrderChangeStatusService orderChangeStatusService;

    @TaskAnnotation("writeSave")
    public Response writeSave(SessionFactory factory, FifteenTables fifteenTables) {
        workTicketService.checkTimeOut(factory, fifteenTables.getWorkTicket().getId(), fifteenTables.getWorkTicket().getUpdateTime());//检查信息是否过期
        String workTicketId = fifteenTablesService.writeSave(factory, fifteenTables);
        return Response.success(workTicketId);
    }

    @TaskAnnotation("getPrintData")
    public List<Print> getPrintData(SessionFactory factory, String id) {
        List<Print> result = fifteenTablesService.getPrintData(factory, id, TicketType.ElectricalFirst.getType());
        return result;
    }

    @TaskAnnotation("writeSubmit")
    public Response writeSubmit(SessionFactory factory, FifteenTables fifteenTables) {
        String workTicketId = fifteenTablesService.writeSubmitByWorkFlowType(factory, fifteenTables, WorkFlowType.ElectricalFirst.getWorkFlow());
        return Response.success(workTicketId);
    }

    @TaskAnnotation("signSave")
    public Response signSave(SessionFactory factory, WorkFlow workFlow) {
        workTicketService.checkTimeOut(factory, workFlow.getWorkTicketId(), workFlow.getUpdateTime());//检查信息是否过期
        workFlowService.save(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("countersignSave")
    public Response countersignSave(SessionFactory factory, WorkFlow workFlow) {
        workTicketService.checkTimeOut(factory, workFlow.getWorkTicketId(), workFlow.getUpdateTime());//检查信息是否过期
        workFlowService.save(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("acceptSave")
    public Response acceptSave(SessionFactory factory, WorkFlow workFlow) {
        workTicketService.checkTimeOut(factory, workFlow.getWorkTicketId(), workFlow.getUpdateTime());//检查信息是否过期
        workFlowService.save(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("permitSave")
    public Response permitSave(SessionFactory factory, WorkPermit workPermit) {
        fifteenTablesService.permitSave(factory, workPermit);
        return Response.success("待许可-提交/保存成功");
    }

    @TaskAnnotation("workEndSave")
    public Response workEndSave(SessionFactory factory, WorkEnd workEnd) {
        fifteenTablesService.endSaveWithStatus(factory, workEnd, TicketStatus.WORK_END.getStatus());
        return Response.success("工作待终结-提交/保存成功");
    }

    @TaskAnnotation("ticketEndSave")
    public Response ticketEndSubmitOrSave(SessionFactory factory, WorkEnd workEnd) {
        fifteenTablesService.endSaveWithStatus(factory, workEnd, TicketStatus.TICKET_END.getStatus());
        return Response.success("工作票待终结-提交/保存成功");
    }

    @TaskAnnotation("workflowUpdate")
    public Response workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        Integer operation = redirectQuery.getOperation();
        String workTicketId = redirectQuery.getDataId();
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = workTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();
        String type = workTicket.getType();

        // 1. 如果被驳回，返回对应状态，仅删除签名的数据，其他的数据不做处理
        if (operation == 1) {
            String rejectNodeCode = redirectQuery.getRejectNodeCode();
            rejectNodeCode = rejectNodeCode.replace("call-", "");
            if (rejectNodeCode.equals(TicketNodeStatus.WRITE.getNodeName())) {
                Integer rejectStatus = TicketStatus.WRITE.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.SIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.SIGN.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.COUNTERSIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.COUNTERSIGN.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.ACCEPT.getNodeName())) {
                Integer rejectStatus = TicketStatus.ACCEPT.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.PERMIT.getNodeName())) {
                Integer rejectStatus = TicketStatus.PERMIT.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                // 20211111: 如何是待许可状态，讲预览标志设置成未预览
                workTicket.setPreviewFlag(1);
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.WORK_END.getNodeName())) {
                Integer rejectStatus = TicketStatus.WORK_END.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
            }
            workTicketService.update(factory, workTicket);
        } // 2. 如果通过，工作票进入下一个状态，并根据状态的不同进行不同的操作
        else if (operation == 32) {
            String formVariables = redirectQuery.getFormVariables();
            // 2.1 如果是签发状态，保存签名信息
            if (status.equals(TicketStatus.WRITE.getStatus())) {
                status = TicketStatus.SIGN.getStatus();
            }
            else if (status.equals(TicketStatus.SIGN.getStatus())) {
                fifteenTablesService.saveWorkFLow(factory, formVariables);
                status = TicketStatus.COUNTERSIGN.getStatus();
                //如果人工决策挑选到待接收
                log.info("人工决策选择:" + redirectQuery.getCurNodeCode());
                if (redirectQuery.getCurNodeCode().equals("call-ACCEPT")) {
                    // 生成工作票号
                    fifteenTablesService.generateCode(factory, workTicket, type);
                    status = TicketStatus.ACCEPT.getStatus();
                }
            } // 2.2 如果是会签状态，保存签名信息，生成工作票号
            else if (status.equals(TicketStatus.COUNTERSIGN.getStatus())) {
                // 保存签名信息
                fifteenTablesService.saveWorkFLow(factory, formVariables);
                // 生成工作票号
                fifteenTablesService.generateCode(factory, workTicket, type);
                status = TicketStatus.ACCEPT.getStatus();
            } // 2.3 如果是待接收状态：1.保存签名信息；2.将预览标志设为未预览
            else if (status.equals(TicketStatus.ACCEPT.getStatus())) {
                // 保存签名信息
                fifteenTablesService.saveWorkFLow(factory, formVariables);
                // 将预览标志设为未预览
                workTicket.setPreviewFlag(1);
                status = TicketStatus.PERMIT.getStatus();
            }
            // 2.4 如果是待许可状态，保存签名信息，以及待许可信息
            else if (status.equals(TicketStatus.PERMIT.getStatus())) {
                // 保存许可信息
                WorkPermit workPermit = JSONObject.parseObject(formVariables, WorkPermit.class);
                workPermit.setId(workPermit.getWorkPermitId());
                workPermit.setPermitTime(new Date());
                workPermitService.save(factory, workPermit);
                // 保存签名信息
                List<WorkFlow> workFlowList = workPermit.getWorkFlowList();
                if (workFlowList != null && workFlowList.size() > 0) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFLow.setId(workFLow.getWorkFlowId());
                        workFlowService.save(factory, workFLow);
                    }
                }
                // 许可后变更工单状态为执行中
                orderChangeStatusService.changeOrderStatus(workTicket.getOrderType(), workTicket.getOrderId());
                status = TicketStatus.WORK_END.getStatus();
            } // 2.5 如果是工作待终结保存签名信息，以及终结信息(工作票待终结直接调用workflowUpdateEnd接口)
            else if (status.equals(TicketStatus.WORK_END.getStatus())) {
                // 保存终结信息
                WorkEnd workEnd = JSONObject.parseObject(formVariables, WorkEnd.class);
                workEnd.setId(workEnd.getWorkEndId());
                workEndService.saveWithStatus(factory, workEnd, TicketStatus.WORK_END.getStatus());
                // 保存签名信息
                List<WorkFlow> workFlowList = workEnd.getWorkFlowList();
                if (workFlowList != null && workFlowList.size() > 0) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFLow.setId(workFLow.getWorkFlowId());
                        workFlowService.save(factory, workFLow);
                    }
                }
                status = TicketStatus.TICKET_END.getStatus();
            }
            // 3. 状态更新，更新主票
            workTicket.setStatus(status);
            workTicketService.update(factory, workTicket);
        } else if (operation == 256) {
            Integer rejectStatus = TicketStatus.WRITE.getStatus();
            fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
            workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
            workTicket.setStatus(rejectStatus);
            workTicketService.update(factory, workTicket);
        } else {
            return Response.fail("操作类型为：" + operation + ",请联系运维人员");
        }

        return Response.success("电气第一种工作票提交成功");
    }

    @TaskAnnotation("workflowUpdateEnd")
    public Response workflowUpdateEnd(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        fifteenTablesService.workflowUpdateEnd(factory, redirectQuery);
        return Response.success("工作票已归档");
    }

    @TaskAnnotation("workflowUpdateCancel")
    public Response workflowUpdateCancel(SessionFactory factory, RedirectQuery redirectQuery) {
        fifteenTablesService.workflowUpdateCancel(factory, redirectQuery);
        return Response.success("工作票已作废");
    }

    public void deleteById(SessionFactory factory, String id) {
        fifteenTablesService.deleteById(factory, id);
    }

    public FifteenTables getById(SessionFactory factory, String id) {
        FifteenTables fifteenTables = fifteenTablesService.getById(factory, id);
        return fifteenTables;
    }

    /**
     * 初始化数据
     */
    public FifteenTables add() {
        FifteenTables fifteenTables = fifteenTablesService.addByType("ElectricalFirst");
        return fifteenTables;
    }


}
